package com.atguigu.gulimall.auth.controller;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.AuthConstant;
import com.atguigu.common.exception.BizCodeEnume;
import com.atguigu.common.utils.R;
import com.atguigu.entity.vo.MemberResponseVo;
import com.atguigu.gulimall.auth.config.ApplicationConfigProperties;
import com.atguigu.gulimall.auth.feign.MemberFeignService;
import com.atguigu.gulimall.auth.feign.ThirdFeignService;
import com.atguigu.gulimall.auth.vo.UserLoginVo;
import com.atguigu.gulimall.auth.vo.UserRegistVo;
import com.mysql.cj.util.TimeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import javax.validation.constraints.NotEmpty;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;




@Controller
public class LoginController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    ThirdFeignService thirdFeignService;

    @Autowired
    MemberFeignService memberFeignService;

    @Autowired
    ApplicationConfigProperties configProperties;

    @ResponseBody
    @GetMapping("/sms/sendCode")
    public R sendCode(@RequestParam("phone") String phone){

        //接口防刷
        //60秒控制,redis中保存值是，带上时间，下次判断时间
        String redisCode = (String) redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + phone);
        if (!StringUtils.isEmpty(redisCode)){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60*1000){
                return R.error(BizCodeEnume.SMS_CODE_EXCEPTION.getCode(),BizCodeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }

        String code = UUID.randomUUID().toString().substring(0, 5);
        String timeCode = code+"_"+System.currentTimeMillis();

        //验证码5分钟有效
        redisTemplate.opsForValue().set(AuthConstant.SMS_CODE_CACHE_PREFIX+phone,timeCode,5, TimeUnit.MINUTES);

        thirdFeignService.sendCode(phone,code);
        return R.ok();
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session){

        Object attribute = session.getAttribute(AuthConstant.LOGIN_USER);
        if (attribute == null){
            //没登录
            return "login";
        }
        return "redirect:"+configProperties.getHost();
    }


    @PostMapping("/login")
    public String login(@Valid UserLoginVo loginVo, BindingResult result,
                        RedirectAttributes attributes, HttpSession session){
        //参数检查
        if (result.hasErrors()){
            Map<String, String> errors = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                if (!errors.keySet().contains(field)){
                    errors.put(fieldError.getField(),fieldError.getDefaultMessage());
                }
            }

            attributes.addFlashAttribute("errors",errors);//只用一次的数据
            return "redirect:"+configProperties.getHost()+"login.html";
        }

        //调用远程登录
        R r = memberFeignService.login(loginVo);
        if (r.getCode() == 0){
            //数据放在session中
            session.setAttribute(AuthConstant.LOGIN_USER,r.getData(new TypeReference<MemberResponseVo>(){}));
            return "redirect:"+configProperties.getHost();
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String >(){}));
            attributes.addFlashAttribute("errors",errors);//只用一次的数据
            return "redirect:"+configProperties.getHost()+"login.html";
        }
    }


    @PostMapping("/regist")
    public String regist(@Valid UserRegistVo userRegistVo, BindingResult result,
                         RedirectAttributes attributes){

        //参数检查
        if (result.hasErrors()){
//            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));

            Map<String, String> errors = new HashMap<>();
            List<FieldError> fieldErrors = result.getFieldErrors();
            for (FieldError fieldError : fieldErrors) {
                String field = fieldError.getField();
                if (!errors.keySet().contains(field)){
                    errors.put(fieldError.getField(),fieldError.getDefaultMessage());
                }
            }
//            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError->{
//                return fieldError.getField();
//            },fieldError -> {
//                return fieldError.getDefaultMessage();
//            }));

//            model.addAttribute("errors",errors);
            attributes.addFlashAttribute("errors",errors);//只用一次的数据
            //前台请求过来是POST请求，失败后转发回去，默认是GET，用POST给GET发请求，会报POST不支持错误
//            return "reg";//转发，有重复提交问题
//            result "forward:/reg.html";//转发
            //校验出错，转发到注册页
            //重定向获取不到mode中的数据,使用RedirectAttributes
            return "redirect:"+configProperties.getHost()+"reg.html";
        }
        //调用远程服务进行注册
        //1.校验验证码
        String code = userRegistVo.getCode();
        String s = (String) redisTemplate.opsForValue().get(AuthConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
        //验证码过期
        if (StringUtils.isEmpty(s)){
            Map<String, String> errors = new HashMap<>();
            errors.put("msg","验证码错误");
            attributes.addFlashAttribute("errors",errors);//只用一次的数据
            return "redirect:"+configProperties.getHost()+"reg.html";
        }

        //验证码错误
        String dbCode = s.split("_")[0];
        if (!code.equals(dbCode)){
            Map<String, String> errors = new HashMap<>();
            errors.put("msg","验证码错误");
            attributes.addFlashAttribute("errors",errors);//只用一次的数据
            return "redirect:"+configProperties.getHost()+"reg.html";
        }

        //验证通过 删除验证码
        redisTemplate.delete(AuthConstant.SMS_CODE_CACHE_PREFIX + userRegistVo.getPhone());
        //调用远程服务
        R r = memberFeignService.regist(userRegistVo);
        if (r.getCode() == 0){
            //注册成功回到首页，回到登录页
            //重定向地址要加上域名，不然会自动从定型到本服务器ip地址，不走网关系统
            return "redirect:"+configProperties.getHost()+"login.html";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg",r.getData("msg",new TypeReference<String>(){}));
            attributes.addFlashAttribute("errors",errors);//只用一次的数据
            return "redirect:"+configProperties.getHost()+"reg.html";
        }
    }
}
